<template>
  <div class="defectLibrary flowCloumn h100">
    <div class="h100">
      <list-table-new
        @focusInput="focusInput"
        @changeInput="changeInput"
        v-bind="tableSetting"
        @selectChange="selectChange"
        @selectAll="selectAll"
        @defaultSelection="checkedUser"
        ref="klTable"
      ></list-table-new>
    </div>
    <dialogPublic
      :title="title"
      :show.sync="show"
      v-if="show"
      @doSubmit="doSubmit"
      @doClose="doClose"
    >
      <editForm
        :formConfig="formConfig"
        ref="editForm"
        :formData="editFormData"
      ></editForm>
      <div class="description">
        <el-form
          ref="form"
          :model="ruleTBForm"
          label-width="80px"
          style="width: 100%"
        >
          <el-row :gutter="20">
            <el-col :span="22">
              <el-form-item label="类似描述1" prop="customs">
                <el-input
                  size="mini"
                  v-model="ruleTBForm.customs"
                  placeholder="请输入类似描述"
                  clearable=""
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="2" style="padding: 0; margin-top: 5px">
              <el-button
                size="mini"
                circle
                type="primary"
                @click="addItem"
                icon="el-icon-plus"
              ></el-button>
            </el-col>
          </el-row>
          <div v-for="(item, index) in ruleTBForm.dynamicItemArr" :key="index">
            <el-row :gutter="20">
              <el-col :span="22">
                <el-form-item
                  :label="`类似描述${index + 2}`"
                  :prop="item.customs"
                >
                  <el-input
                    size="mini"
                    v-model="item.customs"
                    placeholder="请输入类似描述"
                    clearable
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="2" style="padding: 0; margin-top: 5px">
                <el-button
                  size="mini"
                  circle
                  type="danger"
                  @click="deleteItem(item, index)"
                  icon="el-icon-delete"
                ></el-button>
              </el-col>
            </el-row>
          </div>
        </el-form>
      </div>
    </dialogPublic>
    <dialogPublic
      title="合并"
      :show.sync="showContinute"
      @doSubmit="continueMerge"
      @doClose="() => (showContinute = false)"
      :btnText="['继续', '返回']"
    >
      <div style="margin: 50px 0">
        你已勾选了{{ checkData.length }}个关键字，请继续勾选合并的目标关键字
      </div>
    </dialogPublic>
    <dialogPublic
      title="合并:选择目标关键字"
      :show.sync="showMerge"
      width="70%"
      @doSubmit="doMerge"
      @doClose="() => (showMerge = false)"
      :btnText="['确认合并', '返回']"
    >
      <div style="height: 600px" v-if="showMerge">
        <relatePage ref="relatePage" :disableIds="disableIds" :needAdd="false"></relatePage>
      </div>
    </dialogPublic>
    <dialogPublic
      :title="'导入文件'"
      :show.sync="showFile"
      width="40%"
      :noFootBtn="true"
    >
      <div style="text-align: left; height: 200px" v-if="showFile">
        <el-upload
          class="upload-demo"
          :action="uploadUrl"
          :on-change="handleChange"
          :multiple="false"
          :auto-upload="false"
          accept=".xls,.xlsx"
        >
          <el-button slot="trigger" size="small" type="primary"
            >选取文件</el-button
          >
          <el-button
            style="margin-left: 10px"
            size="small"
            type="success"
            @click="submitUpload"
            >上传到服务器</el-button
          >
          <div class="el-upload__tip" slot="tip">
            只能上传excle文件，且不超过500kb
          </div>
        </el-upload>
        <el-button v-if="path != ''" type="text" @click="downLoadResult"
          >下载错误备注文件</el-button
        >
      </div>
    </dialogPublic>
    <dialogPublic
      title="缺陷工单"
      :show.sync="showOrder"
      v-if="showOrder"
      @doClose="() => (showOrder = false)"
      noFootBtn
      :fullscreen="true"
      appendTobody
    >
      <orderList showType="plan"  :queryData="currentRow" ref="orderList" />
    </dialogPublic>
  </div>
</template>
<script>
import {
  queryDefectList,
  saveDefect,
  deleteDefect,
  queryDefectType,
  mergeDefect,
  importdefectStock,
} from "@/api/standardManagement/defectLibrary.js";
import relatePage from "./defectRelatePage.vue";
import orderList from "./defectOrder.vue";
export default {
  components: { relatePage,orderList },
  data() {
    return {
      title: "",
      show: false,
      showFile: false,
      showContinute: false,
      showMerge: false,
      showOrder: false,
      currentRow:{},
      pageType: "list",
      ruleTBForm: {
        customs: "",
        dynamicItemArr: [],
      },
      path: "",
      searchData: {},
      uploadUrl: `${process.env.VUE_APP_BASEURL}/eam-service-standard/defectStock/import`,
      tableSetting: {
        selectionShow: true,
        pageConfig: {
          pageCode: "defectLibrary",
          userId: this.$store.getters.userInfo.id,
        },
        searchObj: {
          searchMethod: (params, sortStr) => {
            this.getTableData(params, sortStr);
          },
          queryData: {
            page: 1,
            pageSize: 15,
            type:["mechatronics","irrigation","property","information","others"]
          },
          searchArr: [
            {
              type: "input",
              label: "缺陷关键字",
              model: "keyword",
              placeholder: "请输入",
            },
            {
              type: "input",
              label: "类似描述",
              model: "others",
              placeholder: "请输入",
            },
            {
              type: "select",
              label: "缺陷类别",
              model: "parentTypeName",
            },
            {
              type: "select",
              label: "缺陷子类",
              model: "typeName",
            },
            {
              type: "datetimerange",
              label: "引用时间",
              model: "refTimes",
              placeholder: "请输入",
            },
            {
              type: "select",
              label: "状态",
              model: "status",
              option: [
                {
                  value: "0",
                  label: "停用",
                },
                {
                  value: "1",
                  label: "启用",
                },
              ],
            },
            {
              type: "organization",
              label: "创建单位",
              model: "deptName",
              idsStr: "deptId",
            },
          ],
        },
        //过滤器的值
        filterFormData: {},
        //过滤器的默认值
        defaultFilterData: {},
        userCustomData: [],
        actionList: [
          {
            name: "新建",
            icon: "el-icon-plus",
            disabled: !this.$store.getters.isBtnAuth("add"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.title = "新增缺陷";
              this.editFormData = {};
              this.show = true;
            },
          },
          {
            name: "删除",
            icon: "el-icon-delete",
            disabled: !this.$store.getters.isBtnAuth("delete"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (index, row) => {
              this.delete();
            },
          },
          {
            name: "合并",
            icon: "el-icon-position",
            disabled: !this.$store.getters.isBtnAuth("merge"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (index, row) => {
              this.merge();
            },
          },
          {
            name: "导入",
            icon: "icon-daoru",
            disabled: !this.$store.getters.isBtnAuth("import"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.showFile = true;
            },
          },
          {
            name: "导出",
            icon: "icon-daochu",
            disabled: !this.$store.getters.isBtnAuth("export"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.export();
            },
          },
          {
            name: "下载模板",
            icon: "icon-xiazai",
            disabled: !this.$store.getters.isBtnAuth("download"), //控制按钮的禁用
            content: "未授权功能", //禁用提示内容
            method: (row) => {
              this.download();
            },
          },
        ],
        column: [
          {
            label: "缺陷类别",
            prop: "parentTypeName",
            sortable: "custom",
          },
          {
            label: "缺陷子类",
            prop: "typeName",
            sortable: "custom",
          },
          {
            label: "缺陷关键字",
            prop: "keyword",
            sortable: "custom",
          },
          {
            label: "类似描述",
            prop: "others",
            sortable: "custom",
          },
          {
            label: "引用次数",
            prop: "num",
            type: "textButton",
            sortable: "custom",
            method: (row, index) => {
              this.currentRow = {realKeys:row.keyword};
              this.showOrder = true;
            },
          },
          {
            label: "最近引用时间",
            prop: "refTime",
            sortable: "custom",
          },
          {
            label: "状态",
            prop: "status",
            sortable: "custom",
            formatter: (row) => {
              return row.status === 1 ? "启用" : "停用";
            },
          },
          {
            label: "创建单位",
            prop: "deptName",
            sortable: "custom",
          },
          {
            label: "创建人",
            prop: "createByName",
            sortable: "custom",
          },
          {
            label: "创建时间",
            prop: "createTime",
            sortable: "custom",
          },
          {
            label: "操作",
            type: "button",
            buttonArr: [
              {
                text: "编辑",
                isShow: () => {
                  return true;
                },
                disabled: !this.$store.getters.isBtnAuth("edit"), //控制按钮的禁用
                content: "未授权功能", //禁用提示内容
                methods: (row, index) => {
                  this.title = "编辑缺陷";
                  this.show = true;
                  this.parentTypeName = row.parentTypeName;
                  this.typeName = row.typeName;
                  this.editFormData = row;
                  this.getFormDefectChild(row.parentTypeName);
                  this.handleCustom();
                },
              },
            ],
          },
        ],
        //表格方法
        tableMethods: {
          //点击行的方法
          rowClick: (row) => {
            // this.title = "编辑缺陷";
            // this.show = true;
            // this.parentTypeName = row.parentTypeName;
            // this.typeName = row.typeName;
            // this.editFormData = row;
            // this.getFormDefectChild(row.parentTypeId);
            // this.handleCustom();
          },
        },
      },
      formConfig: {
        labelWidth: "100px",
        itemArr: [
          {
            label: "缺陷类别",
            prop: "parentTypeName",
            type: "select",
            span: 12,
            placeholder: "请选择或直接输入",
            required: true,
            filterable: true,
            allowCreate: true,
            selectOption: [],
            methods: (arr, item) => {
              this.getFormDefectChild(arr.value);
              if (arr.label) {
                this.parentTypeName = arr.label;
              } else {
                this.parentTypeName = item.parentTypeName;
              }
            },
          },
          {
            label: "缺陷子类",
            prop: "typeName",
            type: "select",
            span: 12,
            placeholder: "请选择或直接输入",
            required: true,
            filterable: true,
            allowCreate: true,
            selectOption: [],
            methods: (arr, item) => {
              if (arr.label) {
                this.typeName = arr.label;
              } else {
                this.typeName = item.typeName;
              }
            },
          },
          {
            label: "缺陷关键字",
            prop: "keyword",
            type: "text",
            span: 12,
            required: true,
          },
          {
            label: "状态",
            prop: "status",
            type: "select",
            span: 12,
            required: true,
            selectOption: [
              { label: "启用", value: 1 },
              { label: "停用", value: 0 },
            ],
          },
        ],
      },
      //弹出框表单数据
      editFormData: {},
      parentTypeName: "", //缺陷分类名
      typeName: "", //缺陷子类名
      others: {},
      checkData: [],
    };
  },
  computed: {
    disableIds() {
      return this.checkData.map((item) => item.id);
    },
  },
  created() {
    this.getDefectType();
  },
  mounted() {
    this.$refs.klTable.getTableConfig();
    this.init();
  },
  methods: {
    //初始化入口
    init() {
      if (this.pageType == "details") {
        this.tableSetting.actionList = [];
      }
      this.$refs.klTable.searchData();
    },
    //表单输入框获取焦点
    focusInput(model, searchForm) {
      if (model === "typeName") {
        if (!searchForm.parentTypeName || searchForm.parentTypeName == "") {
          this.$message.warning("请先选择缺陷类别");
        }
      }
    },
    //
    changeInput(model, searchForm) {
      if (model === "parentTypeName") {
        this.getDefectChild(searchForm.parentTypeName);
      }
    },
    //获取缺陷列表
    getTableData(params, sortStr) {
      let queryData = Object.assign({}, params);
      this.searchData = params;
      let sort = sortStr.concat([
        {
          column: "num",
          asc: false,
        },
        {
          column: "id",
          asc: true,
        },
      ]);
      queryData.orders = sort;
      queryDefectList(queryData).then((res) => {
        this.$set(this.tableSetting, "tableData", res.data.records);
        this.$set(this.tableSetting, "totalNumber", res.data.total);
        this.checkedUser();
      });
    },
    //获取缺陷类型
    getDefectType() {
      queryDefectType().then((res) => {
        let arr = res.data.map((item) => {
          const obj = {
            label: item.parentTypeName,
            value: item.parentTypeName,
          };
          return obj;
        });

        this.$set(this.tableSetting.searchObj.searchArr[2], "option", arr);
        this.$set(this.formConfig.itemArr[0], "selectOption", arr);
      });
    },
    //获取表格表单缺陷子类
    getDefectChild(name) {
      if (name == "") {
        this.$set(this.tableSetting.searchObj.searchArr[3], "option", []);
      } else {
        queryDefectType({ typeName: name }).then((res) => {
          let arr = res.data.map((item) => {
            const obj = {
              label: item.typeName,
              value: item.typeName,
            };
            return obj;
          });
          this.$set(this.tableSetting.searchObj.searchArr[3], "option", arr);
        });
      }
    },
    //勾选已选巡视点
    checkedUser() {
      this.checkData.forEach((item) => {
        this.tableSetting.tableData.forEach((value) => {
          if (value.id == item.id) {
            this.$refs.klTable.selectioned(value);
          }
        });
      });
    },
    selectAll(selected) {
      this.tableSetting.tableData.forEach((item) => {
        this.selectChange(selected, item);
      });
    },
    //添加或取消已选用户
    selectChange(selected, row) {
      if (selected) {
        this.checkData.push(row);
      } else {
        this.checkData.forEach((item, i) => {
          if (item.id === row.id) {
            this.checkData.splice(i, 1);
            return;
          }
        });
      }
    },
    //获取弹框表单的缺陷子类
    getFormDefectChild(name) {
      queryDefectType({ typeName: name }).then((res) => {
        let arr = res.data.map((item) => {
          const obj = {
            label: item.typeName,
            value: item.typeName,
          };
          return obj;
        });
        this.$set(this.formConfig.itemArr[1], "selectOption", arr);
      });
    },
    //回显类似描述的数据，把数据通过分号拆分到几个输入框中
    handleCustom() {
      let entryId = this.editFormData.others;
      if (entryId) {
        if (entryId.indexOf(";") != -1) {
          let customsArr = entryId.split(";");
          this.ruleTBForm.customs = customsArr[0];
          customsArr.forEach((item, index) => {
            if (index + 1 < customsArr.length) {
              this.ruleTBForm.dynamicItemArr.push({
                customs: customsArr[index + 1],
              });
            }
          });
        } else {
          this.ruleTBForm.customs = entryId;
        }
      } else {
        this.ruleTBForm.customs = entryId;
      }
    },
    //添加一行输入框
    addItem() {
      this.ruleTBForm.dynamicItemArr.push({
        custom: "",
      });
    },
    //删除一行输入框
    deleteItem(item, index) {
      this.ruleTBForm.dynamicItemArr.splice(index, 1);
    },
    //通过分号把几个输入框的值拼接起来
    customsHandleConfirm() {
      let entryStr = `${this.ruleTBForm.customs}`;
      if (this.ruleTBForm.dynamicItemArr.length > 0) {
        this.ruleTBForm.dynamicItemArr.forEach((item) => {
          entryStr += `;${item.customs}`;
        });
      }
      return entryStr;
    },
    //提交表单
    async doSubmit() {
      try {
        let formData = await this.$refs.editForm.getFormData();
        formData.others = this.customsHandleConfirm();
        // formData.parentTypeName = this.parentTypeName;
        // formData.typeName = this.typeName;
        let res = await saveDefect(formData);
        this.$message.success(res.description);
        this.show = false;
        this.$refs.klTable.searchData();
        this.getDefectType();
      } catch (error) {
        this.$message.error(error);
      }
    },
    //继续合并
    continueMerge() {
      this.showContinute = false;
      this.showMerge = true;
    },
    //确定合并
    async doMerge() {
      let data = await this.$refs.relatePage.getSelectData();
      let ids = this.checkData.map((item) => item.id);
      let params = {
        sourceIds: ids,
        targetId: data.id,
      };
      let res = await mergeDefect(params);
      this.$message.success(res.description);
      this.$refs.klTable.searchData();
      this.showMerge = false;
      this.checkData = [];
      this.getDefectType();
    },
    //批量删除缺陷
    delete() {
      let arr = this.$refs.klTable.getSelectData();
      let ids = [];
      if (arr.length != 0) {
        this.$confirm("确定要删除选中数据吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            arr.forEach((item) => {
              ids.push(item.id);
            });
            deleteDefect({ ids: ids.join() }).then((res) => {
              if (res.code === 200) {
                this.$message.success(res.description);
                this.$refs.klTable.searchData();
                this.getDefectType();
              }
            });
          })
          .catch((e) => {});
      } else {
        this.$message.warning("请至少勾选一条数据");
      }
    },
    //合并
    merge() {
      if (this.checkData.length > 0) {
        this.showContinute = true;
      } else {
        this.$message.warning("请勾选至少一条数据");
      }
    },
    //关闭弹窗
    doClose() {
      this.ruleTBForm = {
        customs: "",
        dynamicItemArr: [],
      };
      this.show = false;
    },
    //导出
    export() {
      let paramStr = "";
      let params = this.searchData;
      for (const key in params) {
        if (Object.hasOwnProperty.call(params, key)) {
          if (params[key] && params[key] != "") {
            paramStr += `${key}=${params[key]}&`;
          }
        }
      }
      paramStr = paramStr.substring(0, paramStr.length - 1);
      let path = `eam-service-standard/defectStock/export?${paramStr}`;
      let fileName = `缺陷库`;
      this.$utils.downloadFile(null, fileName, path);
    },
    //文件上传之前
    handleChange(file) {
      let formData = new FormData();
      formData.append("file", file.raw);
      this.uploadFile = formData;
    },
    submitUpload() {
      importdefectStock(this.uploadFile).then((res) => {
        if (typeof res.data == "string") {
          this.path = `eam-service-standard/${res.data}`;
          this.$message.error("导入失败，请下载批复文件查看");
        } else {
          this.$message.success("导入成功");
          this.showFile = false;
          this.updateData();
        }
      });
    },
    //点击下载批复文件
    downLoadResult() {
      this.$utils.downloadFile(null, "缺陷库批复明细", this.path);
    },
    download() {
      let path = "eam-service-standard/defectStock/template";
      let fileName = "缺陷库导入模板";
      this.$utils.downloadFile(null, fileName, path);
    },
  },
};
</script>
<style lang="less" scoped>
.defectLibrary {
  padding: 20px;
  .description {
    display: flex;
    margin-left: 15px;
    .action {
      width: 28px;
      height: 28px;
      font-size: 22px;
      text-align: center;
      line-height: 28px;
      cursor: pointer;
    }
  }
}
.flowCloumn {
  display: flex;
  flex-flow: column nowrap;
}
</style>